<template>
  <div>
    <NormalForm :enumOpt="enumOpt" :formList="formList" :operateForm="queryForm" pageTitle="分布分析"
                @handleQuery="handleQuery" @handleReset="handleReset" @selectDateType="selectDateType"
    ></NormalForm>
    <!-- 地域分布 -->
    <div class="mainBox">
      <div class="smallLine"></div>
      <div class="mainTitle">
        <span>地域分布</span>
        <el-tabs v-model="activeTab" @tab-click="handleQuery">
          <el-tab-pane label="存量客户" name="1"></el-tab-pane>
          <el-tab-pane label="增量客户" name="2"></el-tab-pane>
        </el-tabs>
      </div>
      <!-- 区域图标 -->
      <div v-loading="loading" class="areaBox">
        <div class="areaItem">
          <div id="chartSeven" class="item"></div>
          <div class="item" style="margin-left: 60px; height: 100%">
            <el-table :data="cityData" :row-style="{ height: '45px' }" max-height="400" style="width: 100%">
              <el-table-column align="center" label="排名" prop="rank">
                <template slot-scope="{ row }">
                  <svg-icon v-show="row.rank == 1" icon-class="first"/>
                  <svg-icon v-show="row.rank == 2" icon-class="second"/>
                  <svg-icon v-show="row.rank == 3" icon-class="third"/>
                  <div v-show="row.rank != 3 && row.rank != 2 && row.rank != 1">
                    {{ row.rank }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column align="center" label="城市" prop="name">
              </el-table-column>
              <el-table-column align="center" label="用户占比" prop="value">
              </el-table-column>
            </el-table>
            <div v-if="btnFlag" class="expandMore">
              <el-button type="text" @click="expandMore">展开更多</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { getAllWeUser } from '@/api/customer/customerManage'
import * as echarts from 'echarts'
import 'echarts-wordcloud'
import china from '../../customerPortrait/map/json/china.json'
import { parseTime } from '@/utils/common'

export default {
  data() {
    return {
      activeTab: '1',
      queryForm: {
        dateType: '0',
        dateRange: null,
        deptId: null,
        createCode: null,
        insuranceType: null
      },
      formList: [
        {
          label: '渠道',
          value: '',
          prop: 'insuranceType',
          type: 'SELECT',
          emunName: 'insuranceList'
        },
        {
          label: '管理机构',
          value: null,
          prop: 'deptId',
          type: 'MANAGE_COM',
          emunName: ''
        },
        {
          label: '创建人',
          value: '',
          prop: 'createCode',
          type: 'SELECT',
          emunName: 'creatorList'
        },
        {
          label: '',
          value: '',
          prop: 'dateType',
          type: 'SPECIAL_SELECT',
          emunName: 'dateTypeList'
        },
        {
          label: '',
          value: null,
          prop: 'dateRange',
          type: 'SPECIAL_DATE',
          emunName: '',
          aboutProp: 'dateType',
          pickerOptions: {
            disabledDate(time) {
              return time.getTime() > Date.now()
            }
          }
        }
      ],
      enumOpt: {
        insuranceList: [],
        creatorList: [],
        dateTypeList: [
          { dictLabel: '自然日', dictValue: '0' },
          { dictLabel: '自然周', dictValue: '1' },
          { dictLabel: '自然月', dictValue: '2' },
          { dictLabel: '自然年', dictValue: '3' }
        ]
      },
      loading: false,
      cityData: [],
      allCityData: [],
      btnFlag: false //展开按钮
    }
  },
  watch: {
    'queryForm.deptId': {
      handler() {
        if (this.queryForm.deptId) this.getAllWeUserInfo()
      }
    }
  },
  created() {
    this.getLabelList()
    this.selectDateType()
    this.handleQuery()
  },
  methods: {
    getLabelList() {
      // 渠道
      this.getDicts('insurance_type').then((res) => {
        if (res.code === 200) {
          this.enumOpt.insuranceList = res.data
        }
      })
    },
    getAllWeUserInfo() {
      this.enumOpt.creatorList = []
      const params = {
        deptId: this.queryForm.deptId,
        userName: ''
      }
      getAllWeUser(params).then(res => {
        if (res.code === 200) {
          res.data.forEach(item => {
            this.enumOpt.creatorList.push({
              dictLabel: item.userName,
              dictValue: item.userId
            })
          })
        }
      })
    },
    selectDateType() {
      let startTime = parseTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 7), '{y}-{m}-{d}')
      let endTime = parseTime(new Date(new Date().getTime()), '{y}-{m}-{d}')
      if (this.queryForm.dateType === '0') {
        this.queryForm.dateRange = [startTime, endTime]
      } else {
        this.queryForm.dateRange = startTime
      }
    },
    handleQuery() {
      // let obj = this.reassembly();
      // const params = {
      //   dateType: obj.dateType,
      //   startDate: obj.startTime,
      //   endDate: obj.endTime,
      //   deptId: this.queryForm.deptId,
      //   createCode: this.queryForm.createCode,
      //   insuranceType: this.queryForm.insuranceType,
      //   flag: this.activeTab,
      // };
      // this.loading = true;
      // distributionQuery(params).then((res) => {
      //   if (res.code === 200) {
      //     res.data.cityList.forEach((item, index) => {
      //       item.rank = index + 1;
      //     });
      //     this.allCityData = res.data.cityList;
      //     if (this.allCityData.length > 6) {
      //       this.cityData = this.allCityData.slice(0, 6);
      //       this.btnFlag = true;
      //     } else {
      //       this.cityData = this.allCityData;
      //     }
      //     this.getCharts(res.data.provinceList);
      //     this.loading = false;
      //   }
      //   this.loading = false;
      // })
      let getCityList = new Array()
      let num1 = 0
      let num2 = 0
      if (this.activeTab == '1') {
        getCityList = [
          { name: '无锡市', value: '28.33%' },
          { name: '江阴市', value: '18.56%' },
          { name: '扬州市', value: '13.78%' },
          { name: '苏州市', value: '11.65%' },
          { name: '南通市', value: '10.85%' },
          { name: '溧阳市', value: '6.65%' },
          { name: '昆山市', value: '5.33%' },
          { name: '芜湖市', value: '2.1%' },
          { name: '淮安市', value: '1.85%' },
          { name: '宜兴市', value: '0.9%' }
        ]
        num1 = 8
        num2 = 137
      } else {
        getCityList = [
          { name: '无锡市', value: '46.15%' },
          { name: '江阴市', value: '30.77%' },
          { name: '扬州市', value: '23.08%' },
          { name: '苏州市', value: '7.7%' }
        ]
        num1 = 0
        num2 = 13
      }
      const getData = {
        'riskInfoResDTOList': null,
        'provinceList': [
          {
            'name': '北京',
            'value': '0'
          },
          {
            'name': '天津',
            'value': '0'
          },
          {
            'name': '河北',
            'value': '0'
          },
          {
            'name': '山西',
            'value': '0'
          },
          {
            'name': '内蒙古',
            'value': '0'
          },
          {
            'name': '辽宁',
            'value': '0'
          },
          {
            'name': '吉林',
            'value': '0'
          },
          {
            'name': '黑龙江',
            'value': '0'
          },
          {
            'name': '上海',
            'value': '0'
          },
          {
            'name': '江苏',
            'value': num2
          },
          {
            'name': '浙江',
            'value': '0'
          },
          {
            'name': '安徽',
            'value': num1
          },
          {
            'name': '福建',
            'value': '0'
          },
          {
            'name': '江西',
            'value': '0'
          },
          {
            'name': '山东',
            'value': '0'
          },
          {
            'name': '河南',
            'value': '0'
          },
          {
            'name': '湖北',
            'value': '0'
          },
          {
            'name': '湖南',
            'value': '0'
          },
          {
            'name': '广东',
            'value': '0'
          },
          {
            'name': '广西',
            'value': '0'
          },
          {
            'name': '海南',
            'value': '0'
          },
          {
            'name': '四川',
            'value': '0'
          },
          {
            'name': '贵州',
            'value': '0'
          },
          {
            'name': '云南',
            'value': '0'
          },
          {
            'name': '西藏',
            'value': '0'
          },
          {
            'name': '陕西',
            'value': '0'
          },
          {
            'name': '甘肃',
            'value': '0'
          },
          {
            'name': '青海',
            'value': '0'
          },
          {
            'name': '宁夏',
            'value': '0'
          },
          {
            'name': '新疆',
            'value': '0'
          },
          {
            'name': '台湾',
            'value': '0'
          },
          {
            'name': '香港',
            'value': '0'
          },
          {
            'name': '澳门',
            'value': '0'
          },
          {
            'name': '重庆',
            'value': '0'
          }
        ],
        'cityList': getCityList
      }
      getData.cityList.forEach((item, index) => {
        item.rank = index + 1
      })
      this.allCityData = getData.cityList
      if (this.allCityData.length > 6) {
        this.cityData = this.allCityData.slice(0, 6)
        this.btnFlag = true
      } else {
        this.cityData = this.allCityData
      }
      window.setTimeout(() => {
        this.getCharts(getData.provinceList)
      }, 1000)
    },
    handleReset() {
      let startTime = parseTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 7), '{y}-{m}-{d}')
      let endTime = parseTime(new Date(new Date().getTime()), '{y}-{m}-{d}')
      this.enumOpt.creatorList = []
      this.queryForm = {
        dateType: '0',
        dateRange: [startTime, endTime],
        deptId: null,
        createCode: null,
        insuranceType: null
      }
      this.handleQuery()
    },
    expandMore() {
      //展开更多
      this.btnFlag = false
      this.cityData = this.allCityData
    },
    // 组装startTime和endTime入参
    reassembly() {
      let startTime = null, endTime = null, dateType = null
      let selectDate = this.queryForm.dateRange
      if (selectDate) {
        if (this.queryForm.dateType === '0') {
          dateType = 'DAY' // 日
          startTime = selectDate[0]
          endTime = selectDate[1]
        } else if (this.queryForm.dateType === '1') {
          dateType = 'DAY' // 周
          startTime = parseTime(new Date(new Date(selectDate).getTime() - 24 * 60 * 60 * 1000), '{y}-{m}-{d}')
          endTime = parseTime(new Date(new Date(selectDate).getTime() + 5 * 24 * 60 * 60 * 1000), '{y}-{m}-{d}')
        } else if (this.queryForm.dateType === '2') {
          dateType = 'MONTH' // 月
          startTime = selectDate
          const temp = selectDate.split('-')
          let str = +temp[1] + 1
          temp[1] = temp[1] < 9 ? '0' + str : str
          if (temp[1] === 13) {
            temp[1] = '01'
            temp[0] = +temp[0] + 1
          }
          endTime = temp.join('-')
        } else if (this.queryForm.dateType === '3') {
          dateType = 'YEAR' // 年
          startTime = selectDate
          const temp = selectDate.split('-')
          temp[0] = +temp[0] + 1
          endTime = temp.join('-')
        }
      }
      return { startTime, endTime, dateType }
    },
    //图表
    getCharts(provinceList) {
      var chartDom = document.getElementById('chartSeven')
      var myChart = echarts.init(chartDom)
      echarts.registerMap('china', china)
      var nameColor = ' rgb(55, 75, 113)'
      var name_fontFamily = '等线'
      var subname_fontSize = 15
      var name_fontSize = 18
      var mapName = 'china'
      var data = provinceList
      var geoCoordMap = {}
      /*获取地图数据*/
      myChart.showLoading()
      var mapFeatures = echarts.getMap(mapName).geoJson.features
      myChart.hideLoading()
      // console.log(mapFeatures, "mapFeatures");
      mapFeatures.forEach(function(v) {
        // 地区名称
        var name = v.properties.name
        // 地区经纬度
        geoCoordMap[name] = v.properties.cp
      })

      var convertData = function(data) {
        var res = []
        for (var i = 0; i < data.length; i++) {
          var geoCoord = geoCoordMap[data[i].name]
          if (geoCoord) {
            res.push({
              name: data[i].name,
              value: geoCoord.concat(data[i].value)
            })
          }
          return res
        }
      }
      var option = {
        title: {
          x: 'center',
          textStyle: {
            color: nameColor,
            fontFamily: name_fontFamily,
            fontSize: name_fontSize
          },
          subtextStyle: {
            fontSize: subname_fontSize,
            fontFamily: name_fontFamily
          }
        },

        visualMap: {
          show: true,
          min: 0,
          max: 200,
          left: 'right',
          top: 'bottom',
          text: ['高', '低'], // 文本，默认为数值文本
          seriesIndex: [1],
          calculable: true,
          inRange: {
            color: ['#EBEEFF', '#082aff'] // 蓝黑
          }
        },

        geo: {
          show: true,
          map: mapName,
          label: {
            normal: {
              show: false
            },
            emphasis: {
              show: false
            }
          },
          // roam: true,
          itemStyle: {
            normal: {
              areaColor: '#031525',
              borderColor: '#3B5077'
            },
            emphasis: {
              areaColor: '#2B91B7'
            }
          }
        },
        series: [
          {
            name: '散点',
            type: 'scatter',
            coordinateSystem: 'geo',
            data: convertData(data),
            symbolSize: function(val) {
              return val[2] / 10
            },
            label: {
              normal: {
                formatter: '{b}',
                position: 'right',
                show: true
              },
              emphasis: {
                show: true
              }
            },
            itemStyle: {
              normal: {
                color: '#05C3F9'
              }
            }
          },
          {
            type: 'map',
            map: mapName,
            geoIndex: 0,
            aspectScale: 0.75, //长宽比
            showLegendSymbol: false, // 存在legend时显示
            label: {
              normal: {
                show: true
              },
              emphasis: {
                show: false,
                textStyle: {
                  color: '#fff'
                }
              }
            },
            roam: true,
            itemStyle: {
              normal: {
                areaColor: '#031525',
                borderColor: '#3B5077'
              },
              emphasis: {
                areaColor: '#2B91B7'
              }
            },
            animation: false,
            data: data
          }
        ]
      }
      option && myChart.setOption(option)
    }
  }
}
</script>
<style lang="scss" scoped>
@import "@/styles/element-ui.scss";
@import "@/styles/base.scss";

.wrap {
  @include titleWrap;
  margin-top: 20px;
}

.mainBox {
  margin-top: 16px;
  width: 100%;
  background: #ffffff;
  border-radius: 8px;
  padding: 16px 20px;

  .mainTitle {
    font-size: 16px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #333333;
  }

  .smallLine {
    width: 4px;
    height: 20px;
    background: #082aff;
    position: absolute;
    left: 8px;
  }
}

.areaBox {
  width: 100%;
  margin-left: -20px;
  margin-top: 16px;
  padding-bottom: 30px;

  .areaItem {
    width: 100%;
    height: 442px;
    padding-right: 40px;
    box-sizing: border-box;
    display: flex;

    .item {
      flex: 1;
    }

    #chartFour {
      margin-right: 16px;
    }
  }
}

.el-tabs {
  padding-right: 50px;
}

::v-deep {
  .el-tabs__nav-wrap {
    display: flex;
    justify-content: flex-end;
  }
}

.expandMore {
  text-align: center;
}
</style>
